package com.augrain.microframework.trace.instrument.web;

import com.augrain.microframework.trace.TraceProperty;
import com.augrain.microframework.trace.common.TraceLabel;
import com.augrain.microframework.trace.context.TraceContext;
import com.augrain.microframework.trace.util.MDCUtils;
import com.augrain.microframework.trace.util.TraceUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * trace追踪web层拦截器
 *
 * @author biaoy
 * @since 2021/08/20
 */
public class TraceWebLogInterceptor implements HandlerInterceptor {

    private final TraceProperty traceProperty;

    public TraceWebLogInterceptor(TraceProperty traceProperty) {
        this.traceProperty = traceProperty;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 构建traceLabel
        TraceLabel traceLabel = TraceUtils.build(request);
        // 设置到线程上下文中
        TraceContext.setTraceLabel(traceLabel);
        // 设置到MDC中
        MDCUtils.put(traceLabel, traceProperty);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TraceContext.clear();
        MDCUtils.clear();
    }
}
